package com.gitee.leijin.rbac.security.handler;

import cn.hutool.json.JSONUtil;
import com.gitee.leijin.rbac.util.AjaxUtils;
import com.gitee.leijin.rbac.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
@Component
public class LoginAuthenticationFailureHandler implements AuthenticationFailureHandler {

    /**
     * 不要在此处(Filter)中抛出异常
     * SpringSecurity是在Filter中处理认证，授权的处理，如果抛出异常，全局处理器 {@link com.gitee.leijin.rbac.exception.MvcExHandler} 拦截不到
     * MvcExHandler 只能处理Controller或者拦截器抛出的异常，详情见 {@link org.springframework.web.servlet.DispatcherServlet#doDispatch}
     * 如果需要处理Filter中抛出的异常，需要重写{@link org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController}
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        Result<String> loginResult = Result.failure("用户名或密码不正确");
        AjaxUtils.response(response, JSONUtil.toJsonStr(loginResult));
    }


}
